package com.molichuxing.services.business;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.services.business.dto.request.create.IdentityCreateDto;
import com.molichuxing.services.business.service.IdentityBizService;
import com.molichuxing.services.infrastructure.dto.request.create.GztIdverifyNotifyLogCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.GztIdverifyRequestLogCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.PyIdverifyNotifyLogCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.PyIdverifyRequestLogCreateDto;
import com.molichuxing.services.infrastructure.service.GztIdverifyNotifyLogService;
import com.molichuxing.services.infrastructure.service.GztIdverifyRequestLogService;
import com.molichuxing.services.infrastructure.service.PyIdverifyNotifyLogService;
import com.molichuxing.services.infrastructure.service.PyIdverifyRequestLogService;
import com.molichuxing.services.sdk.gzt.GztUtil;
import com.molichuxing.services.sdk.py.response.CisReport;
import com.molichuxing.services.sdk.py.response.PyResponseBean;
import com.molichuxing.services.sdk.py.response.face.FaceComparisionInfo;
import com.molichuxing.services.sdk.py.response.face.Item;
import com.molichuxing.services.util.PyParamsUtil;
/**
 * 
 * @author liyg
 * 身份认证服务实现类
 * 2019-09-20
 *
 */
@Service("identityBizService")
public class IdentityBizServiceImpl implements IdentityBizService{
	
	private static Logger logger = Logger.getLogger(IdentityBizServiceImpl.class);

	@Value("${py.host}")
	private String host;
	@Value("${py.path}")
	private String path;
	@Value("${py.user.id}")
	private String userId;
	@Value("${py.password}")
	private String password;
	
	private final static String PY_RESULT_FALSE="建议拒绝";
	
	@Autowired
	private GztIdverifyNotifyLogService gztIdverifyNotifyLogService;
	    
	@Autowired
	private GztIdverifyRequestLogService gztIdverifyRequestLogService;
	
	@Autowired
	private PyIdverifyNotifyLogService pyIdverifyNotifyLogService;
	
	@Autowired
	private PyIdverifyRequestLogService pyIdverifyRequestLogService;
	
	
	/**
	 * 人脸识别
	 * @param createDto
	 * @return
	 */
	@Override
	public ResponseResult<String> getFaceIdentity(IdentityCreateDto createDto) {
		String realName=createDto.getRealName();
		String idNumber=createDto.getIdNumber();
		String photo=createDto.getPhoto();
		String compressPhoto = createDto.getCompressPhoto();
		Integer requestId = saveRequestGzt(realName,idNumber,photo);
		String responeXml =null;
		try {
			GztUtil.getClient();
			logger.info("国政通人脸识别入参:"+"realName:"+"  idNumber:"+idNumber);
			responeXml = GztUtil.verifyIdentity(realName, idNumber, photo);
			logger.info("国政通人脸识别出参:"+responeXml);
		} catch (Exception e) {
			logger.error("国政通接口异常:",e);
			GztIdverifyNotifyLogCreateDto logCreateDto= new GztIdverifyNotifyLogCreateDto();
			logCreateDto.setRequestId(requestId);
			logCreateDto.setResult("500");
			logCreateDto.setMessage("调用国政通人脸识别接口异常");
			gztIdverifyNotifyLogService.create(logCreateDto);
			return getPyData(realName, idNumber, compressPhoto);
		}
		ResponseResult<String> response = getGztResult(responeXml,photo,realName,idNumber,requestId);
		if(response.getCode().equals(110)) {
			return getPyData(realName, idNumber, compressPhoto);
		}
		return response;
	}
	
	/**
	 * 获取鹏元数据
	 * @param realName
	 * @param idNumber
	 * @param photo
	 * @return
	 */
	private ResponseResult<String> getPyData(String realName, String idNumber, String photo){
		String result=null;
		Integer requestId = saveRequestPy(realName,idNumber,photo);
		try {
			String params = PyParamsUtil.getIdentityParam(realName, idNumber, photo);
			logger.info("鹏元人脸识别start");
			result = PyParamsUtil.requestApi(host, path, userId,password,params);
			logger.info("鹏元人脸识别出参"+result);
		} catch (Exception e) {
			logger.error("鹏元人脸识别接口异常:",e);
			PyIdverifyNotifyLogCreateDto logCreateDto= new PyIdverifyNotifyLogCreateDto();
			logCreateDto.setRequestId(requestId);
			logCreateDto.setExternalStatus("500");
			logCreateDto.setMessage("调用鹏元人脸识别接口异常");
			pyIdverifyNotifyLogService.create(logCreateDto);
			return new ResponseResult<>(1,"很抱歉，您未通过身份证验证",null);
		}
		return  getPyResult(photo,realName,idNumber,requestId,result);
	}
	
	/**
	 * 解析国政通 身份认证返回数据
	 * @param responeXml
	 * @param photo
	 * @param fullName
	 * @param idNumber
	 * @return
	 */
	private ResponseResult<String> getGztResult(String responeXml, String photo, String fullName,
			String idNumber,Integer requestId ){
		GztIdverifyNotifyLogCreateDto createDto= new GztIdverifyNotifyLogCreateDto();
		createDto.setRequestId(requestId);
		if(StringUtils.isBlank(responeXml)) {
			createDto.setResult("500");
			createDto.setMessage("调用国政通人脸识别接口返回数据为空");
			gztIdverifyNotifyLogService.create(createDto);
			return new ResponseResult<>(1,"很抱歉，您未通过身份证验证",null);
		}
		
		JSONObject json = JSONObject.parseObject(responeXml);
		// 0: 比对服务处理成功  
		String result = json.getString("result");
		createDto.setResult(result);
		//返回结果述
		String message = json.getString("message");
		try {
			if (StringUtils.isNoneBlank(message)) {
				message = java.net.URLDecoder.decode(message, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		createDto.setMessage(message);
		//对比服务交易编号 
		String transactionId = json.getString("transaction_id");
		createDto.setTransactionId(transactionId);
		//身份信息核验结果 1 库中无此号 2 不一致 3 一致 4 核查失败 
		String userCheckResult = json.getString("user_check_result");
		createDto.setUserCheckResult(userCheckResult);
		//对比结果 0、表示认为是同一个人  1、表示认为不是同一个人
		String verifyResult = json.getString("verify_result");
		createDto.setVerifyResult(verifyResult);
		//对比相似值 分数取值范围 0 – 100, 值越大越相似 
		String verifySimilarity = json.getString("verify_similarity");
		createDto.setVerifySimilarity(verifySimilarity);
        //保存日志
		gztIdverifyNotifyLogService.create(createDto);
		
		if(!"0".equals(result)) {
			logger.error("《国政通》 0: 比对服务处理成功  result="+result);
			return new ResponseResult<>(110,"调用鹏元接口",null);
		}
		if(!"3".equals(userCheckResult)) {
			logger.error("《国政通》 0: 身份信息核验结果 1 库中无此号 2 不一致 3 一致 4 核查失败  userCheckResult="+userCheckResult);
			return new ResponseResult<>(1,"很抱歉，您未通过身份证验证",null);
		}
		if(!"0".equals(verifyResult)) {
			logger.error("《国政通》 对比结果 0、表示认为是同一个人  1、表示认为不是同一个人   verifyResult="+verifyResult);
			return new ResponseResult<>(1,"很抱歉，您未通过身份证验证",null);
		}
		return new ResponseResult<String>().success();
	}
	
	/**
	 * 解析鹏元 身份认证返回数据
	 * @param pyResponseBean
	 * @param photo
	 * @param fullName
	 * @param idNumber
	 * @return
	 */
	private ResponseResult<String> getPyResult(String photo, String fullName,
			String idNumber,Integer requestId,String result) {
		
		PyIdverifyNotifyLogCreateDto createDto=new PyIdverifyNotifyLogCreateDto();
		createDto.setRequestId(requestId);
		if(StringUtils.isBlank(result)) {
			createDto.setExternalStatus("500");
			createDto.setExternalErrorMessage("调用鹏元人脸识别接口返回数据为空");
			pyIdverifyNotifyLogService.create(createDto);
			return new ResponseResult<>(1, "很抱歉，您未通过身份证验证", null);
		}
		
		PyResponseBean pyResponseBean = JSONObject.parseObject(result, PyResponseBean.class);
		//保存鹏元返回参数
		savePyRespone(pyResponseBean,result,createDto);
		
		if (null != pyResponseBean && "1".equals(pyResponseBean.getStatus())) {
			List<CisReport> cisReports = pyResponseBean.getReturnValue().getCisReport();
			if(null == cisReports || cisReports.isEmpty()) {
				logger.error("《鹏元》  鹏元cisReports为空");
				return new ResponseResult<>(1, "很抱歉，您未通过身份证验证", null);
			}
			
			for (CisReport cisReport : cisReports) {

				if ("true".equals(cisReport.getHasSystemError()) || "true".equals(cisReport.getIsFrozen())) {
					logger.error("《鹏元》  鹏元系统错误||该客户是否被冻结");
					return new ResponseResult<>(1, "很抱歉，您未通过身份证验证", null);
				}
				
				FaceComparisionInfo faceComparisionInfo = cisReport.getFaceComparisionInfo();
				if(null == faceComparisionInfo) {
					logger.error("《鹏元》 faceComparisionInfo为空");
					return new ResponseResult<>(1, "很抱歉，您未通过身份证验证", null);
				}
				// 1：查得，2：未查得，3：其它原因未查得
				Integer treatResult =faceComparisionInfo.getTreatResult();
				if(null == treatResult) {
					logger.error("《鹏元》 子报告查询状态  未查得");
					return new ResponseResult<>(1, "很抱歉，您未通过身份证验证", null);
				}else if (treatResult != 1) {
					logger.error("《鹏元》 子报告查询状态  未查得");
					return new ResponseResult<>(1, "很抱歉，您未通过身份证验证", null);
				}
				Item item = faceComparisionInfo.getItem();
				if (null == item.getValidateResult() || PY_RESULT_FALSE.equals(item.getValidateResult().trim())) {
					logger.error("《鹏元》 比对结果建议信息  建议拒绝 ");
					return new ResponseResult<>(1, "很抱歉，您未通过身份证验证", null);
				}
			}
			return new ResponseResult<String>().success();
		} 
		return new ResponseResult<>(1, "很抱歉，您未通过身份证验证", null);
	}
	
	/**
	 * 保存鹏元接口返回数据
	 * @param pyResponseBean
	 * @param result
	 */
	private void savePyRespone(PyResponseBean py,String result,PyIdverifyNotifyLogCreateDto createDto) {
		
		createDto.setExternalStatus(py.getStatus());
		createDto.setExternalErrorMessage(py.getErrorMessage());
		createDto.setExternalErrorCode(py.getErrorCode());
		createDto.setExternalResponse(result);
		if(null != py && "1".equals(py.getStatus())) {
			List<CisReport> cisReports = py.getReturnValue().getCisReport();
			
			FaceComparisionInfo faceComparisionInfo=null;
			Item item=null;
			if(null != cisReports && cisReports.size()>0) {
				CisReport cisReport = cisReports.get(0);
				createDto.setIsFrozen(cisReport.getIsFrozen());
				createDto.setHasSystemError(cisReport.getHasSystemError());
				faceComparisionInfo = cisReport.getFaceComparisionInfo();
			}
			
			if(null != faceComparisionInfo) {
				createDto.setTreatResult(faceComparisionInfo.getTreatResult());
				createDto.setErrorMessage(faceComparisionInfo.getErrorMessage());
				createDto.setTreatErrorCode(faceComparisionInfo.getTreatErrorCode());
				item = faceComparisionInfo.getItem();
			}
			
			if(null != item) {
				createDto.setIsNameValid(item.getIsNameValid());
				createDto.setIsPhotoCompared(item.getIsPhotoCompared());
				createDto.setSimilarity(item.getSimilarity());
				createDto.setValidateResult(item.getValidateResult());
				createDto.setMessage(item.getMessage());
			}
		}
		pyIdverifyNotifyLogService.create(createDto);
	}
	/**
	 * 保存请求国政通日志
	 * @param realName
	 * @param idNumber
	 * @param photo
	 * @return
	 */
	private Integer saveRequestGzt(String realName, String idNumber, String photo){
		GztIdverifyRequestLogCreateDto createDto=new GztIdverifyRequestLogCreateDto();
		createDto.setUserId(idNumber);
		createDto.setUserName(realName);
		createDto.setFaceImg(photo);
		return gztIdverifyRequestLogService.create(createDto);
	}
	
	/**
	 * 保存请求鹏元日志
	 * @param realName
	 * @param idNumber
	 * @param photo
	 * @return
	 */
	private Integer saveRequestPy(String realName, String idNumber, String photo){
		PyIdverifyRequestLogCreateDto createDto=new PyIdverifyRequestLogCreateDto();
		createDto.setUserId(idNumber);
		createDto.setUserName(realName);
		createDto.setFaceImg(photo);
		return pyIdverifyRequestLogService.create(createDto);
	}
}
